package cn.stylefeng.guns.sys.core.listener;

import cn.stylefeng.guns.sys.modular.system.model.result.BtyCwHpDto;
import cn.stylefeng.guns.sys.modular.system.service.BtyCwHuopeiService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.SneakyThrows;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class BtyCwHpListener extends AnalysisEventListener<BtyCwHpDto> {
    private BtyCwHuopeiService btyCwHuopeiService;

    public BtyCwHpListener(){

    }

    public BtyCwHpListener(BtyCwHuopeiService btyCwHuopeiService){
        this.btyCwHuopeiService = btyCwHuopeiService;
    }


    /**
     * 批处理阈值2000
     * 每隔100条存储数据库，然后清理list，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    List<BtyCwHpDto> list = new ArrayList<BtyCwHpDto>();
    List<String> codeList = new ArrayList();
    String begin = "";
    String end = "";

    /**
     * 每一条数据解析都会来调用
     */
    @SneakyThrows
    @Override
    public void invoke(BtyCwHpDto basic, AnalysisContext analysisContext) {
        //餐具（包含山西餐具） 及 山西酒水不统计
        if(ToolUtil.isNotEmpty(basic.getShopCode()) && !basic.getClassName().contains("餐具") && !basic.getClassName().contains("山西") && !basic.getShopCode().equals("门店编号")){
            if (basic.getClassName().contains("酒水")){
                basic.setPrice("0");//非税成本单价
                basic.setAmountTotal("0");//耗用金额分差
            }
            basic.setBegin(begin);
            basic.setEnd(end);
            codeList.add(basic.getShopCode());
            list.add(basic);
        }

        System.out.println("======" + list);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
            codeList.clear();
        }
    }

    /**
     * 这里会一行行的返回头
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        String name = headMap.get(0);
        begin = name.split("业务日期:|至|\\)")[1];
        end = name.split("业务日期:|至|\\)")[2];

        System.out.println(headMap);
    }

    /**
     * 所有数据解析完成了 都会来调用
     */
    @SneakyThrows
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        analysisContext.readWorkbookHolder().setDefaultReturnMap(false);
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        // 当然也可以有很多其他操作 比如有些需要触发其他的 可以在这里调用
        saveData();
        // log.info("所有数据解析完成！");

    }

    /**
     * 存储数据库
     */
    private void saveData() throws Exception {
        //调用saveData()方法
        btyCwHuopeiService.insertHp(list, codeList, end, begin);
    }
}
